package com.yangyang.rpc.core.registry.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

/**
 * zk服务注册
 * Created by chenshunyang on 2016/11/27.
 */
public class ZkServiceRegistry{
    private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegistry.class);

    private static CountDownLatch latch = new CountDownLatch(1);

    public static void register(int port,String zkList, Set<String> serviceSet){
        // init address: ip : port
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        }
        if (ip == null) {
            return;
        }
        String serverAddress = ip + ":" + port;

        if (serverAddress != null) {
            ZooKeeper zk = ZookeeperManager.getInstance(zkList);
            if (zk != null) {
                addRootNode(zk); // Add root node if not exist
                createNode(zk, serverAddress,serviceSet);
            }
        }
    }


    private static void addRootNode(ZooKeeper zk) {
        try {
            Stat stat = zk.exists(Constant.ZK_REGISTRY_PATH, false);
            if (stat == null) {
                zk.create(Constant.ZK_REGISTRY_PATH, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
            LOGGER.error("",e);
            e.printStackTrace();
        } catch (InterruptedException e) {
            LOGGER.error("",e);
            e.printStackTrace();
        }
    }

    private static void createNode(ZooKeeper zk, String data, Set<String> serviceSet) {
        byte[] bytes = data.getBytes();
        try {
            for (String interfaceName :serviceSet) {
                if (interfaceName == null || interfaceName.equals("")) {
                    continue;
                }
                //会话结束时节点会自动删除，OPEN_ACL_UNSAFE开放所有权限
                String path = zk.create(Constant.ZK_REGISTRY_PATH+"/"+interfaceName, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                LOGGER.debug("create zookeeper node ({} => {})", path, data);
            }
//			//会话结束时节点会自动删除，OPEN_ACL_UNSAFE开放所有权限
//			String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
//			LOGGER.debug("create zookeeper node ({} => {})", path, data);
        } catch (KeeperException e) {
            LOGGER.error("",e);
            e.printStackTrace();
        } catch (InterruptedException e) {
            LOGGER.error("",e);
            e.printStackTrace();
        }
    }

}
